<?php
/**
 * 二维码生成API接口
 * 基于base64_encoding_test.php的方法
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// 只允许POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => '只允许POST请求']);
    exit;
}

// 获取请求数据
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    http_response_code(400);
    echo json_encode(['error' => '无效的JSON数据']);
    exit;
}

// 验证必需参数
$text = $input['text'] ?? '';
if (empty($text)) {
    http_response_code(400);
    echo json_encode(['error' => '缺少必需参数: text']);
    exit;
}

// 获取可选参数
$size = (int)($input['size'] ?? 300);
$errorCorrection = $input['error_correction'] ?? 'L';
$margin = (int)($input['margin'] ?? 4);
$moduleSize = (int)($input['module_size'] ?? 3);

// 验证参数范围
$size = max(100, min(1000, $size)); // 限制在100-1000之间
$margin = max(0, min(10, $margin)); // 限制在0-10之间
$moduleSize = max(1, min(10, $moduleSize)); // 限制在1-10之间

// 验证错误纠正级别
$validErrorLevels = ['L', 'M', 'Q', 'H'];
if (!in_array($errorCorrection, $validErrorLevels)) {
    $errorCorrection = 'L';
}

try {
    // 检查phpqrcode库
    $lib_path = __DIR__ . '/../libs/phpqrcode/qrlib.php';
    if (!file_exists($lib_path)) {
        throw new Exception('phpqrcode库文件不存在');
    }
    
    require_once $lib_path;
    
    if (!class_exists('QRcode')) {
        throw new Exception('QRcode类未找到');
    }
    
    // 清理输出缓冲，避免影响二维码生成
    while (ob_get_level()) {
        ob_end_clean();
    }
    
    // 生成二维码PNG数据
    $png_data = QRcode::png($text, false, constant('QR_ECLEVEL_' . $errorCorrection), $moduleSize, $margin);
    
    if (!$png_data || strlen($png_data) === 0) {
        throw new Exception('二维码生成失败');
    }
    
    // 验证PNG数据
    if (strlen($png_data) < 100) {
        throw new Exception('生成的PNG数据过短');
    }
    
    // 检查PNG文件头
    $header = substr($png_data, 0, 8);
    if ($header !== "\x89PNG\r\n\x1a\n") {
        throw new Exception('生成的不是有效的PNG数据');
    }
    
    // 生成base64编码
    $base64_data = base64_encode($png_data);
    
    if (!$base64_data) {
        throw new Exception('Base64编码失败');
    }
    
    // 构建完整的data URI
    $data_uri = 'data:image/png;base64,' . $base64_data;
    
    // 返回成功结果
    echo json_encode([
        'success' => true,
        'data' => [
            'base64' => $data_uri,
            'raw_base64' => $base64_data,
            'size' => strlen($png_data),
            'text' => $text,
            'options' => [
                'size' => $size,
                'error_correction' => $errorCorrection,
                'margin' => $margin,
                'module_size' => $moduleSize
            ]
        ],
        'message' => '二维码生成成功'
    ]);
    
} catch (Exception $e) {
    error_log("二维码生成API错误: " . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'message' => '二维码生成失败'
    ]);
} catch (Error $e) {
    error_log("二维码生成API错误: " . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => '系统错误: ' . $e->getMessage(),
        'message' => '二维码生成失败'
    ]);
}
?>
